#include "tlogger.h"
#ifdef WIN32
#include <windows.h>
#else
#endif
namespace tlib
{
TLogger g_log;
TLogger::TLogger()
{
  m_nLogFileTime = 0;
  m_pLogFile = NULL;
  tlib::GetExeName(m_pFilePath, 256);
}

TLogger::~TLogger()
{
  if (m_pLogFile)
  {
    fclose(m_pLogFile);
    m_pLogFile = NULL;
  }
}

void TLogger::OpenFile(char* file)
{

  if (m_pLogFile)
  {
    fclose(m_pLogFile);
    m_pLogFile = NULL;
  }
  m_pLogFile = fopen(file, "a + ");
  fprintf(m_pLogFile, "\n\n");
  fprintf(m_pLogFile, "====================================================\n");
  fprintf(m_pLogFile, "====================STARTRUN========================\n");
  fprintf(m_pLogFile, "====================================================\n");
  fprintf(m_pLogFile, "\n\n");
}

void TLogger::WriteLog(const char* level, const char* fmt, ...)
{
  //#if TRUE
  TAutoLock lock(&m_mutex);
  va_list args;
  va_start(args, fmt);
  vsprintf(m_pWriteBuf, fmt, args);
  va_end(args);

  int tid = CurrThreadId();
  time_t atimer = time(NULL);
  struct tm* area = localtime(&atimer);
  int time = ((area->tm_year + 1900) * 100) + ((area->tm_mon + 1) * 10000) + (area->tm_mday * 100) + area->tm_hour;

  if (m_nLogFileTime < time)
  {
    m_nLogFileTime = time;
    char file[256];
    sprintf(file, "%s.%04d%02d%02d%02d.log", m_pFilePath, area->tm_year + 1900, area->tm_mon + 1, area->tm_mday, area->tm_hour);
    OpenFile(file);
  }
  fprintf(m_pLogFile, "%04d-%02d-%02d %02d:%02d:%02d TID:%05d %5s - %s\n", area->tm_year + 1900, area->tm_mon + 1, area->tm_mday, area->tm_hour, area->tm_min, area->tm_sec, tid,
      level, m_pWriteBuf);
  fflush(m_pLogFile);
  printf("%04d-%02d-%02d %02d:%02d:%02d TID:%05d %5s - %s\n", area->tm_year + 1900, area->tm_mon + 1, area->tm_mday, area->tm_hour, area->tm_min, area->tm_sec, CurrThreadId(),
      level, m_pWriteBuf);
  //#endif
}
}
